package com.shujia.scala

import scala.io.Source

object Demo26SumScore {
  def main(args: Array[String]): Unit = {
    /**
     * 统计学生总分
     *
     */
    //1、读取分数表
    val lines: List[String] = Source.fromFile("data/score.txt").getLines().toList


    //2、取出学号和分数
    val idAndScore: List[(String, Int)] = lines.map((line: String) => {
      val split: Array[String] = line.split(",")
      //学号
      val id: String = split.head
      //分数
      val score: Int = split.last.toInt
      //返回学号和分数
      (id, score)
    })

    //3、按照学号分组
    val groupByMap: Map[String, List[(String, Int)]] = idAndScore.groupBy((kv: (String, Int)) => kv._1)


    //4、计算总分
    val sumScore4List: Map[String, Int] = groupByMap.map((kv: (String, List[(String, Int)])) => {
      //学号
      val id: String = kv._1

      //取出一个人所有的我分数
      val scoresList: List[(String, Int)] = kv._2
      val scores: List[Int] = scoresList.map((kv: (String, Int)) => kv._2)
      //计算总分
      val sumScore: Int = scores.sum

      //返回结果
      (id, sumScore)
    })

    sumScore4List.foreach(println)

  }

}
